package com.example.daily.ui.viewmodel

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.daily.data.UserPreferences
import com.example.daily.data.api.ChatRequest
import com.example.daily.data.api.DeepSeekApi
import com.example.daily.data.api.Message
import com.example.daily.data.dao.ChatMessageDao
import com.example.daily.data.dao.FoodRecordDao
import com.example.daily.data.entity.ChatMessage
import com.example.daily.data.entity.FoodRecord
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import java.time.*
import javax.inject.Inject

@HiltViewModel
class AiConsultViewModel @Inject constructor(
    private val chatMessageDao: ChatMessageDao,
    private val foodRecordDao: FoodRecordDao,
    private val userPreferences: UserPreferences,
    private val deepSeekApi: DeepSeekApi
) : ViewModel() {

    private val _messageInput = MutableStateFlow("")
    val messageInput: StateFlow<String> = _messageInput

    private var _messages: StateFlow<List<ChatMessage>>? = null
    val messages: StateFlow<List<ChatMessage>>?
        get() = _messages

    // 获取今日食物记录
    private val _foodRecords = MutableStateFlow<List<FoodRecord>>(emptyList())
    val foodRecords: StateFlow<List<FoodRecord>> = _foodRecords

    private val apiKey = "Bearer sk-88a21ccddbde4eec8898fb7ee057b1ff"

    init {
        viewModelScope.launch {
            try {
                val userId = userPreferences.getUserId().first()
                Log.d("AiConsultViewModel", "初始化 - 用户ID: $userId")
                
                if (userId != null) {
                    _messages = chatMessageDao.getMessagesForUser(userId)
                        .stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())
                    
                    // 加载今日食物记录
                    loadTodayFoodRecords(userId)
                } else {
                    Log.e("AiConsultViewModel", "用户ID为空")
                }
            } catch (e: Exception) {
                Log.e("AiConsultViewModel", "初始化失败", e)
            }
        }
    }

    private suspend fun loadTodayFoodRecords(userId: Int) {
        try {
            // 获取当前时区的今天开始和结束时间
            val now = LocalDate.now()
            val zoneId = ZoneId.systemDefault()
            val startOfDay = now.atStartOfDay(zoneId).toInstant().toEpochMilli()
            val endOfDay = now.plusDays(1).atStartOfDay(zoneId).toInstant().toEpochMilli()
            
            Log.d("AiConsultViewModel", "加载今日食物记录")
            Log.d("AiConsultViewModel", "当前时间: ${System.currentTimeMillis()}")
            Log.d("AiConsultViewModel", "开始时间: $startOfDay")
            Log.d("AiConsultViewModel", "结束时间: $endOfDay")
            
            foodRecordDao.getFoodRecordsForUserInTimeRange(userId, startOfDay, endOfDay)
                .collect { records ->
                    Log.d("AiConsultViewModel", "获取到食物记录: ${records.size}条")
                    records.forEach { record ->
                        Log.d("AiConsultViewModel", "食物记录: ${record.foodName}, 时间: ${record.recordDate}")
                    }
                    _foodRecords.value = records
                }
        } catch (e: Exception) {
            Log.e("AiConsultViewModel", "加载食物记录失败", e)
        }
    }

    fun onMessageInputChange(input: String) {
        _messageInput.value = input
    }

    fun appendToMessage(content: String) {
        _messageInput.value = _messageInput.value + content
    }

    fun sendMessage() {
        val messageContent = _messageInput.value.trim()
        if (messageContent.isBlank()) return

        viewModelScope.launch {
            val userId = userPreferences.getUserId().first() ?: return@launch
            
            // 保存用户消息
            val userMessage = ChatMessage(
                userId = userId,
                content = messageContent,
                isUser = true
            )
            chatMessageDao.insertMessage(userMessage)

            try {
                // 调用DeepSeek API
                val response = deepSeekApi.chat(
                    apiKey = apiKey,
                    request = ChatRequest(
                        messages = listOf(
                            Message(
                                role = "user",
                                content = messageContent
                            )
                        )
                    )
                )

                // 保存AI响应
                val aiMessage = ChatMessage(
                    userId = userId,
                    content = response.choices.firstOrNull()?.message?.content ?: "抱歉，我现在无法回答这个问题。",
                    isUser = false
                )
                chatMessageDao.insertMessage(aiMessage)
            } catch (e: Exception) {
                // 保存错误消息
                val errorMessage = ChatMessage(
                    userId = userId,
                    content = "抱歉，发生了一个错误：${e.message}",
                    isUser = false
                )
                chatMessageDao.insertMessage(errorMessage)
            }
            
            // 清空输入
            _messageInput.value = ""
        }
    }

    fun clearChat() {
        viewModelScope.launch {
            val userId = userPreferences.getUserId().first() ?: return@launch
            chatMessageDao.clearUserMessages(userId)
        }
    }
} 